<?php
session_start();
//ini_set('display_errors',1);
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/database.php');
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/functions.php');
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/class.admin.php');
require($_SERVER['DOCUMENT_ROOT'].'/resources/lib/class.image.php');
$admin=new admin();
$admin->canView($_SERVER['PHP_SELF']);

//$admin=new admin();
// image
$im=new image();
$namespace	=	$_FILES['media'];
$image_name	=	$namespace['name'];
$tmp_name	=	$namespace['tmp_name'];
$size		=	$namespace['size'];
$ext=strtolower(end(explode(".",$image_name)));
// goto database and shit ...
$oid=$_POST['content_editor'];
$data=new database();
$data->db(DATABASE)->collection('media')->id();
$media_id=(string)$data->id;
$im->input($tmp_name)->thumb($_SERVER['DOCUMENT_ROOT'].'/media/'.$media_id.'_thumb.'.$ext)->build();
$thumb['width']=$im->outWidth;
$thumb['height']=$im->outHeight;

$im->input($tmp_name)->large($_SERVER['DOCUMENT_ROOT'].'/media/'.$media_id.'_large.'.$ext)->build();
$large['width']=$im->outWidth;
$large['height']=$im->outHeight;
if($ext=='png') {
	exec("/usr/bin/optipng ".$_SERVER['DOCUMENT_ROOT'].'/media/'.$media_id.'_thumb.'.$ext."");
	exec("/usr/bin/optipng ".$_SERVER['DOCUMENT_ROOT'].'/media/'.$media_id.'_large.'.$ext."");
}
move_uploaded_file($tmp_name,$_SERVER['DOCUMENT_ROOT'].'/media/'.$media_id.'.'.$ext);

/*
so we can attach it to the DB field
$im->width;
$im->height;
$im->thumbWidth;
$im->thumbHeight;
*/
$item=array('_id'=>$data->id,
			'path'=>'/media/'.$media_id.'.'.$ext,
			'ext'=>$ext,
			'dimensions'=>array('width'=>intval($im->width),'height'=>intval($im->height)),
			'large'=>array('width'=>intval($large['width']),'height'=>intval($large['height']),'path'=>'/media/'.$media_id.'_large.'.$ext),
			'thumb'=>array('width'=>intval($thumb['width']),'height'=>intval($thumb['height']),'path'=>'/media/'.$media_id.'_thumb.'.$ext),
			'date'=>intval(time()));
			
$data->criteria($item)->insert($item);

?>
<script>
top.load_media_gallery("#images-gallery","<?php echo($oid); ?>");
</script>